/**
 * chenuu.com
 * 
 * @author  zhaoxu.com@gmail.com
 * @created 2012-11-3
 */
package com.chenuu.integration.httpclient.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Encoder;

import com.chenuu.common.exceptions.ChenuuException;
import com.chenuu.integration.httpclient.RequestParameter;

/**
 *
 */
public class RequestUtil {

	private static final String ENCODING = "UTF-8";

	public static String encode(String s) {
		try {
			return URLEncoder.encode(s, ENCODING);
		} catch (UnsupportedEncodingException e) {
			// 不会出现这个异常。
		}

		return null;
	}

	public static String signature(String s, String key, String method) {

		if (s == null || method == null) {
			throw new ChenuuException("参数不能为空。［s=" + s + ",method=" + method + "］");
		}

		if (method.equals("HMAC-SHA1")) {
			try {
				SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "HMACSHA1");

				Mac mac = Mac.getInstance("HMACSHA1");
				mac.init(secretKeySpec);
				byte[] byteHmac = mac.doFinal(s.getBytes());

				return new BASE64Encoder().encode(byteHmac);
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvalidKeyException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else if (method.equals("RSA-SHA1")) {
			throw new ChenuuException("不支持的签名方式。［method=" + method + "］");
		} else if (method.equals("PLAINTEXT")) {
			throw new ChenuuException("不支持的签名方式。［method=" + method + "］");
		} else {
			throw new ChenuuException("不支持的签名方式。［method=" + method + "］");
		}

		return null;
	}

	public static String buildURI(String uri, List<RequestParameter> params) {

		uri = uri.replaceAll(" ", "%20");
		
		if (params == null || params.size() == 0) {
			return uri;
		}

		String requestUrl = uri;
		boolean isFirst = true;
		for (RequestParameter param : params) {
			if (isFirst) {
				requestUrl += "?";
				isFirst = false;
			} else {
				requestUrl += "&";
			}
			requestUrl += param;
		}

		return requestUrl;
	}
}
